﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;

namespace Mengsk.ERP.Phone
{

    public class PhoneResult
    {
        public string Mobile;
        public string QueryResult;
        public string TO;
        public string Corp;
        public string Province;
        public string City;
        public string AreadCode;
        public string PostCode;
        public string VNO;
        public string Card;
    }


    public class PhoneUtil
    {
        static DataContractJsonSerializer sizeSer = new DataContractJsonSerializer(typeof(PhoneResult));
        static string API_URL = "http://v.showji.com/locating/showji.com.aspx?m={0}&output=json&callback=querycallback&timestamp={1}";
        //static string API_URL = "http://api.showji.com/Locating/www.show.ji.c.o.m.aspx?m={0}&output=json&callback=querycallback&timestamp={1}";
        public static PhoneResult GetPhoneAddress(String phone, int retryCount = 10)
        {
            Exception ex = null;
            for (int i = 0; i < retryCount; i++)
            {
                try
                {
                    String query = string.Format(API_URL, phone, (long)DateTime.Now.Subtract(new DateTime(1970, 01, 01, 00, 00, 00)).TotalMilliseconds);
                    Debug.WriteLine(query);
                    String content = Encoding.UTF8.GetString(Http.HttpUtil.DownladContent(query)).Trim();
                    content = content.Substring(0, content.Length - 2).Substring("querycallback(".Length);
                    PhoneResult pr = sizeSer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(content))) as PhoneResult;
                    return pr;
                }
                catch (Exception e)
                {
                    Thread.Sleep(250 * (i + 1));
                    ex = e;
                }
            }
            throw ex;

        }
    }
}
